package priv.mill.controller;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import priv.mill.controller.util.RetenObj;
import priv.mill.entry.Answer;
import priv.mill.server.AnswerService;

@Controller
@RequestMapping("Answer")
public class AnswerController {

	@Autowired
	private AnswerService AnswerService;

	private static final Logger logger = Logger.getLogger(AnswerController.class);

	@RequestMapping("getAnswerById")
	@ResponseBody
	public RetenObj getAnswerById(@RequestParam("AnswerId") Integer AnswerId) {
		try {
			return warpData(AnswerService.getAnswerById(AnswerId), 200);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return warpData(null, 500);
		}
	}

	private RetenObj warpData(Object object, int i) {
		RetenObj retenObj = new RetenObj();
		retenObj.setData(object);
		retenObj.setStatus(i);
		return retenObj;
	}

	@RequestMapping("getAnswerByEntry")
	@ResponseBody
	public RetenObj getAnswerByEntry(Answer Answer) {
		try {
			return warpData(AnswerService.getAnswerByEntry(Answer), 200);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return warpData(null, 500);
		}
	}

	@RequestMapping("getAnswersByPage")
	@ResponseBody
	public RetenObj getAnswersByPage(Answer Answer) {
		try {
			return warpData(AnswerService.getAnswersByPage(Answer), 200);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return warpData(null, 500);
		}
	}

	@RequestMapping("updateAnswer")
	@ResponseBody
	public RetenObj updateAnswer(Answer Answer) {
		try {
			int result = AnswerService.updateAnswer(Answer);
			if (result > 0)
				return warpData(result, 200);
			else
				return warpData(result, 300);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return warpData(null, 500);
		}
	}
	

	@RequestMapping("insertAnswer")
	@ResponseBody
	public RetenObj insertAnswer(Answer Answer) {
		try {
			int result = AnswerService.insertAnswer(Answer);
			if (result > 0)
				return warpData(Answer.getAnswerId(), 200);
			else
				return warpData(result, 300);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return warpData(null, 500);
		}
	}

	@RequestMapping("deleteAnswer")
	
	@ResponseBody
	public RetenObj deleteAnswer(Integer AnswerId) {
		try {
			int result = AnswerService.deleteAnswer(AnswerId);
			if (result > 0)
				return warpData(result, 200);
			else
				return warpData(result, 300);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return warpData(null, 500);
		}

	}
}
